package com.dmai.capacity.platform.gateway.chain;

import com.dmai.capacity.platform.gateway.constants.ErrorCodeConstant;
import com.dmai.capacity.platform.gateway.service.IRateLimitService;
import org.apache.commons.chain.Command;
import org.apache.commons.chain.Context;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

import com.dmai.capacity.platform.common.dto.ResponseEntity;
import com.dmai.capacity.platform.common.properties.SecurityProperties;
import com.dmai.capacity.platform.gateway.context.SecurityContext;
import com.dmai.capacity.platform.gateway.utils.TokenUtil;

/**
 * 限流命令
 */
@Component
public class RateLimitCommand implements Command {

    @Autowired
    private IRateLimitService rateLimitService;

    @Autowired
    private SecurityProperties securityProperties;


    @Override
    public boolean execute(Context context) throws Exception {
        if (securityProperties.getRatelimit().getEnable()) {
            SecurityContext securityContext = (SecurityContext) context;
            ServerHttpRequest request = securityContext.getExchange().getRequest();
            String accessToken = TokenUtil.extractToken(request);
            String reqUrl = request.getPath().value();
            // 超额自增处理
            boolean flag = rateLimitService.checkRateLimit(reqUrl, accessToken);
            // 超额限流
            if (flag) {
                securityContext.setCode(HttpStatus.TOO_MANY_REQUESTS.value());
                securityContext.setEntity(ResponseEntity.of(ErrorCodeConstant.TOO_MANY_REQUESTS_COES, "触发接口限流，请重试", null));
                securityContext.setResult(true);
                return true;
            }
        }

        return false;
    }

}
